<template>
  <div class="device-control-demo">
    <el-page-header @back="$router.back()">
      <template #content>
        <span class="text-large font-600 mr-3">设备控制演示</span>
      </template>
    </el-page-header>

    <el-row :gutter="20" class="demo-content">
      <!-- Device List -->
      <el-col :span="8">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>设备列表</span>
              <el-button size="small" @click="refreshDevices" :loading="loading">
                刷新
              </el-button>
            </div>
          </template>

          <el-empty v-if="devices.length === 0" description="暂无设备" />
          
          <el-space direction="vertical" fill style="width: 100%" v-else>
            <el-card 
              v-for="device in devices" 
              :key="device.id"
              shadow="hover"
              @click="selectDevice(device)"
              :class="{ 'active-device': selectedDevice?.id === device.id }"
              class="device-item"
            >
              <div class="device-info">
                <div class="device-name">{{ device.name || device.id }}</div>
                <el-tag size="small" :type="device.status === 'device' ? 'success' : 'info'">
                  {{ device.status }}
                </el-tag>
              </div>
              <div class="device-id">{{ device.id }}</div>
            </el-card>
          </el-space>
        </el-card>
      </el-col>

      <!-- Control Panel -->
      <el-col :span="16">
        <DeviceControl 
          v-if="selectedDevice"
          :device-id="selectedDevice.id"
          @update:connected="handleConnectionUpdate"
        />
        
        <el-empty v-else description="请选择一个设备">
          <el-button type="primary" @click="refreshDevices">扫描设备</el-button>
        </el-empty>
      </el-col>
    </el-row>

    <!-- Automation Scripts -->
    <el-card class="automation-section" v-if="selectedDevice && deviceConnected">
      <template #header>
        <span>自动化脚本示例</span>
      </template>

      <el-row :gutter="20">
        <el-col :span="6" v-for="script in automationScripts" :key="script.id">
          <el-card shadow="hover" class="script-card">
            <div class="script-info">
              <el-icon size="24" :color="script.color">
                <component :is="script.icon" />
              </el-icon>
              <h4>{{ script.name }}</h4>
              <p>{{ script.description }}</p>
            </div>
            <el-button 
              type="primary" 
              size="small" 
              @click="runScript(script)"
              :loading="runningScripts.includes(script.id)"
            >
              运行脚本
            </el-button>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <!-- Log Output -->
    <el-card class="log-section" v-if="logs.length > 0">
      <template #header>
        <div class="card-header">
          <span>操作日志</span>
          <el-button size="small" @click="clearLogs">清空</el-button>
        </div>
      </template>

      <div class="log-container">
        <div v-for="(log, index) in logs" :key="index" class="log-item">
          <el-tag size="small" :type="log.type">{{ log.type }}</el-tag>
          <span class="log-time">{{ log.time }}</span>
          <span class="log-message">{{ log.message }}</span>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { 
  Promotion, 
  ChatDotRound, 
  Camera, 
  VideoPlay 
} from '@element-plus/icons-vue';
import DeviceControl from '@/components/DeviceControl.vue';
import { DeviceControl as DeviceControlAPI } from '@/api/device-control';
import { AndroidKeycode } from '@/types/android-events';

interface Device {
  id: string;
  name?: string;
  status: string;
}

interface AutomationScript {
  id: string;
  name: string;
  description: string;
  icon: any;
  color: string;
  actions: ScriptAction[];
}

interface ScriptAction {
  type: 'tap' | 'swipe' | 'text' | 'key' | 'wait' | 'screenshot';
  params?: any;
}

interface LogEntry {
  type: 'info' | 'success' | 'warning' | 'error';
  time: string;
  message: string;
}

// State
const devices = ref<Device[]>([]);
const selectedDevice = ref<Device | null>(null);
const deviceConnected = ref(false);
const loading = ref(false);
const runningScripts = ref<string[]>([]);
const logs = ref<LogEntry[]>([]);

let deviceControl: DeviceControlAPI | null = null;

// Automation Scripts
const automationScripts = ref<AutomationScript[]>([
  {
    id: 'open-app',
    name: '打开应用',
    description: '演示打开应用商店',
    icon: Promotion,
    color: '#409eff',
    actions: [
      { type: 'key', params: { keycode: AndroidKeycode.KEYCODE_HOME } },
      { type: 'wait', params: { duration: 500 } },
      { type: 'swipe', params: { direction: 'up', distance: 300 } },
      { type: 'wait', params: { duration: 500 } },
      { type: 'text', params: { text: 'Play Store' } },
      { type: 'wait', params: { duration: 1000 } },
      { type: 'tap', params: { x: 540, y: 400 } },
    ]
  },
  {
    id: 'send-message',
    name: '发送消息',
    description: '模拟发送文本消息',
    icon: ChatDotRound,
    color: '#67c23a',
    actions: [
      { type: 'text', params: { text: 'Hello from automation!' } },
      { type: 'wait', params: { duration: 500 } },
      { type: 'key', params: { keycode: AndroidKeycode.KEYCODE_ENTER } },
    ]
  },
  {
    id: 'take-screenshot',
    name: '截图操作',
    description: '截图并保存',
    icon: Camera,
    color: '#e6a23c',
    actions: [
      { type: 'screenshot', params: {} },
      { type: 'wait', params: { duration: 1000 } },
    ]
  },
  {
    id: 'media-control',
    name: '媒体控制',
    description: '播放/暂停媒体',
    icon: VideoPlay,
    color: '#f56c6c',
    actions: [
      { type: 'key', params: { keycode: AndroidKeycode.KEYCODE_MEDIA_PLAY_PAUSE } },
      { type: 'wait', params: { duration: 2000 } },
      { type: 'key', params: { keycode: AndroidKeycode.KEYCODE_VOLUME_UP } },
      { type: 'wait', params: { duration: 500 } },
      { type: 'key', params: { keycode: AndroidKeycode.KEYCODE_VOLUME_DOWN } },
    ]
  },
]);

// Methods
async function refreshDevices() {
  loading.value = true;
  try {
    // Simulate getting devices from ADB
    // In real implementation, this would call the actual ADB command
    const mockDevices: Device[] = [
      { id: 'emulator-5554', name: 'Android Emulator', status: 'device' },
      { id: '192.168.1.100:5555', name: 'Network Device', status: 'device' },
    ];
    
    devices.value = mockDevices;
    addLog('info', `发现 ${mockDevices.length} 个设备`);
  } catch (error) {
    ElMessage.error('获取设备列表失败');
    addLog('error', `获取设备失败: ${error}`);
  } finally {
    loading.value = false;
  }
}

function selectDevice(device: Device) {
  selectedDevice.value = device;
  addLog('info', `选择设备: ${device.id}`);
}

function handleConnectionUpdate(connected: boolean) {
  deviceConnected.value = connected;
  if (connected) {
    addLog('success', `设备 ${selectedDevice.value?.id} 已连接`);
  } else {
    addLog('info', `设备 ${selectedDevice.value?.id} 已断开`);
  }
}

async function runScript(script: AutomationScript) {
  if (!deviceControl) {
    deviceControl = new DeviceControlAPI(selectedDevice.value!.id);
    await deviceControl.start();
  }

  runningScripts.value.push(script.id);
  addLog('info', `开始执行脚本: ${script.name}`);

  try {
    for (const action of script.actions) {
      await executeAction(action);
    }
    addLog('success', `脚本 ${script.name} 执行完成`);
    ElMessage.success(`脚本 ${script.name} 执行完成`);
  } catch (error) {
    addLog('error', `脚本执行失败: ${error}`);
    ElMessage.error(`脚本执行失败: ${error}`);
  } finally {
    runningScripts.value = runningScripts.value.filter(id => id !== script.id);
  }
}

async function executeAction(action: ScriptAction) {
  switch (action.type) {
    case 'tap':
      await deviceControl?.tap(action.params.x, action.params.y);
      addLog('info', `点击: (${action.params.x}, ${action.params.y})`);
      break;
      
    case 'swipe':
      const { direction, distance } = action.params;
      if (direction === 'up') await deviceControl?.swipeUp(distance);
      else if (direction === 'down') await deviceControl?.swipeDown(distance);
      else if (direction === 'left') await deviceControl?.swipeLeft(distance);
      else if (direction === 'right') await deviceControl?.swipeRight(distance);
      addLog('info', `滑动: ${direction} ${distance}px`);
      break;
      
    case 'text':
      await deviceControl?.sendText(action.params.text);
      addLog('info', `输入文本: ${action.params.text}`);
      break;
      
    case 'key':
      await deviceControl?.sendKeyPress(action.params.keycode);
      addLog('info', `按键: ${AndroidKeycode[action.params.keycode]}`);
      break;
      
    case 'wait':
      await new Promise(resolve => setTimeout(resolve, action.params.duration));
      addLog('info', `等待: ${action.params.duration}ms`);
      break;
      
    case 'screenshot':
      // This would call the screenshot API
      addLog('info', '截图已保存');
      break;
  }
}

function addLog(type: LogEntry['type'], message: string) {
  const now = new Date();
  const time = now.toLocaleTimeString('zh-CN');
  logs.value.unshift({ type, time, message });
  
  // Keep only last 50 logs
  if (logs.value.length > 50) {
    logs.value = logs.value.slice(0, 50);
  }
}

function clearLogs() {
  logs.value = [];
}

// Lifecycle
onMounted(() => {
  refreshDevices();
});
</script>

<style scoped>
.device-control-demo {
  padding: 20px;
}

.demo-content {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.device-item {
  cursor: pointer;
  transition: all 0.3s;
}

.device-item:hover {
  transform: translateX(5px);
}

.device-item.active-device {
  border-color: #409eff;
  background: #ecf5ff;
}

.device-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.device-name {
  font-weight: 500;
  font-size: 14px;
}

.device-id {
  color: #909399;
  font-size: 12px;
}

.automation-section {
  margin-top: 20px;
}

.script-card {
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.script-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.script-info {
  padding: 20px 0;
}

.script-info h4 {
  margin: 10px 0;
  font-size: 14px;
}

.script-info p {
  color: #909399;
  font-size: 12px;
  margin: 0;
}

.log-section {
  margin-top: 20px;
}

.log-container {
  max-height: 300px;
  overflow-y: auto;
  background: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
}

.log-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 5px 0;
  border-bottom: 1px solid #ebeef5;
  font-size: 12px;
}

.log-item:last-child {
  border-bottom: none;
}

.log-time {
  color: #909399;
  min-width: 80px;
}

.log-message {
  flex: 1;
  color: #303133;
}
</style>